<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */

    public function __construct()
    {
        parent::__construct();
		$this->load->model('login_model');
		$this->load->model('Evento_model');
		$this->load->library(array('session','form_validation', 'email'));
		$this->load->helper(array('url','form'));
		$this->load->database('default');
    }


	public function index()
	{
		switch ($this->session->userdata('perfil')) {
		case '':
			$data['token'] = $this->token();

			$this->load->model('Evento_model');
			$tipos = $this->Evento_model->getTipos();
			$categorias = $this->Evento_model->getCategorias();

			$selectorTipos = array();
			$selectorCategorias = array();
			while($tablerow = mysql_fetch_array($tipos)) 
			{
	 			 $selectorTipos[$tablerow['id_tipo']] = $tablerow['nombre'];
			}
			while($tablerow = mysql_fetch_array($categorias)) 
			{
	 			 $selectorCategorias[$tablerow['id_categoria']] = $tablerow['nombre'];
			}
			$data['tipos'] = $selectorTipos;
			$data['categorias'] = $selectorCategorias;

	      	$listaEventos = $this->Evento_model->getEventos();
      		$eventos = array('rs_eventos' => $listaEventos);

      		$datos["inicio"] = 'class="current_page_item"';
			$datos["contact"] = '';
			$datos["unete"] = '';
			$datos["acercaDe"] = '';
			$v_page["header"] = $this->load->view("header.php", $datos , TRUE);

			$v_page["banner"] = $this->load->view("banner.html", '' , TRUE);
			$v_page["leftside"] = $this->load->view("leftside", $data , TRUE);

			$mostrarEventos["body"] = $this->load->view("mostrar_eventos", $eventos , TRUE);
			$v_page["centralgrid"] = $this->load->view("centralgrid", $mostrarEventos , TRUE);

			$login["body"] = $this->load->view("login_view", $data, TRUE);
			$login["header"] = "Con&eacutectate";
			$v_page["rightside"] = $this->load->view("rightside", $login , TRUE);
			
			$v_page["footer"] = $this->load->view("footer.html", '' , TRUE);
			$this->load->view('index', $v_page);
			break;
		case 'administrador':
			redirect(base_url().'index.php/administrador');
			break;
		case 'editor':
			redirect(base_url().'index.php/editor');
			break;
		case 'suscriptor':
			redirect(base_url().'index.php/suscriptor');
			break;	
		default:		
			//$data['titulo'] = 'Login con roles de usuario en codeigniter';
			//$this->load->view('login_view',$data);
			break;		
		}
	}
	
	public function token()
	{
		$token = md5(uniqid(rand(),true));
		$this->session->set_userdata('token',$token);
		return $token;
	}

	public function listByTipo($id_tipo)
	{	
		if (!is_null($this->session->userdata('token')))
		{
			$data['token'] = $this->token();
		} 

		$this->load->model('Evento_model');
		
		$categorias = $this->Evento_model->getCategorias();

		$selectorCategorias = array();
		while($tablerow = mysql_fetch_array($categorias)) {
 			 $selectorCategorias[$tablerow['id_categoria']] = $tablerow['nombre'];
		}
		$data['categorias'] = $selectorCategorias;
		$tipos = $this->Evento_model->getTipos();

		$selectorTipos = array();
		while($tablerow = mysql_fetch_array($tipos)) {
 			 $selectorTipos[$tablerow['id_tipo']] = $tablerow['nombre'];
		}
		$data['tipos'] = $selectorTipos;

      	$listaEventos = $this->Evento_model->getEventosByTipo($id_tipo);
  		$eventos = array('rs_eventos' => $listaEventos);

	  	$datos["inicio"] = '';
		$datos["contact"] = '';
		$datos["unete"] = '';
		$datos["acercaDe"] = '';
  		$v_page["header"] = $this->load->view("header.php", $datos , TRUE);
		$v_page["banner"] = $this->load->view("banner.html", '' , TRUE);
		$v_page["leftside"] = $this->load->view("leftside", $data , TRUE);

		$mostrarEventos["body"] = $this->load->view("mostrar_eventos", $eventos , TRUE);
		$v_page["centralgrid"] = $this->load->view("centralgrid", $mostrarEventos , TRUE);

		$login["body"] = $this->load->view("login_view", $data, TRUE);
		$login["header"] = "Conectate";
		$v_page["rightside"] = $this->load->view("rightside", $login , TRUE);
		
		$v_page["footer"] = $this->load->view("footer.html", '' , TRUE);
		$this->load->view('index', $v_page);
	}
	
	public function listByCategoria($id_categoria)
	{	
		if (!is_null($this->session->userdata('token')))
		{
			$data['token'] = $this->token();
		} 

		$this->load->model('Evento_model');
		
		$tipos = $this->Evento_model->getTipos();

		$selectorTipos = array();
		while($tablerow = mysql_fetch_array($tipos)) {
 			 $selectorTipos[$tablerow['id_tipo']] = $tablerow['nombre'];
		}
		$data['tipos'] = $selectorTipos;
		$categorias = $this->Evento_model->getCategorias();

		$selectorCategorias = array();
		while($tablerow = mysql_fetch_array($categorias)) {
 			 $selectorCategorias[$tablerow['id_categoria']] = $tablerow['nombre'];
		}
		$data['categorias'] = $selectorCategorias;

      	$listaEventos = $this->Evento_model->getEventosByCategoria($id_categoria);
  		$eventos = array('rs_eventos' => $listaEventos);

  		$datos["inicio"] = '';
		$datos["contact"] = '';
		$datos["unete"] = '';
		$datos["acercaDe"] = '';
		$v_page["header"] = $this->load->view("header.php", $datos , TRUE);
		$v_page["banner"] = $this->load->view("banner.html", '' , TRUE);
		$v_page["leftside"] = $this->load->view("leftside", $data , TRUE);

		$mostrarEventos["body"] = $this->load->view("mostrar_eventos", $eventos , TRUE);
		$v_page["centralgrid"] = $this->load->view("centralgrid", $mostrarEventos , TRUE);

		$login["body"] = $this->load->view("login_view", $data, TRUE);
		$login["header"] = "Conectate";
		$v_page["rightside"] = $this->load->view("rightside", $login , TRUE);
		
		$v_page["footer"] = $this->load->view("footer.html", '' , TRUE);
		$this->load->view('index', $v_page);
	}

	public function show_event($id_evento)
	{	
		if (!is_null($this->session->userdata('token')))
		{
			$data['token'] = $this->token();
		} 
		$this->load->model('Evento_model');
		$tipos = $this->Evento_model->getTipos();

		$selectorTipos = array();
		while($tablerow = mysql_fetch_array($tipos)) 
		{
 			 $selectorTipos[$tablerow['id_tipo']] = $tablerow['nombre'];
		}
		$data['tipos'] = $selectorTipos;
		$valor_media = mysql_fetch_assoc($this->Evento_model->getValoracion($id_evento));
		$datos["avg_vot"] = $valor_media["AVG(valoracion)"];
		$this->Evento_model->modifPuntuacion($datos["avg_vot"], $id_evento);
		
		$categorias = $this->Evento_model->getCategorias();

		$selectorCategorias = array();
		while($tablerow = mysql_fetch_array($categorias))
		{
 			 $selectorCategorias[$tablerow['id_categoria']] = $tablerow['nombre'];
		}
		$data['categorias'] = $selectorCategorias;

      	$datos["evento"] = mysql_fetch_assoc($this->Evento_model->getEvento($id_evento));
      	$datos["perfilEvento"] = mysql_fetch_assoc($this->Evento_model->eventProfile($id_evento));
      	$coordenadas["localizacion"] = mysql_fetch_assoc($this->Evento_model->getCoordenadas($id_evento, $datos["evento"]["fecha_ini"], $datos["evento"]["fecha_fin"]));

      	$this->load->library('googlemaps');

      	$posicion = $coordenadas["localizacion"]["lat"].", ".$coordenadas["localizacion"]["long"];
		$config['center'] = $posicion;
		$config['zoom'] = '18';

		$this->googlemaps->initialize($config);

		$marker = array();
		$marker['position'] = $posicion;
		$this->googlemaps->add_marker($marker);
		$datos['map'] = $this->googlemaps->create_map();

		$datos["inicio"] = '';
		$datos["contact"] = '';
		$datos["unete"] = '';
		$datos["acercaDe"] = '';
		$v_page["header"] = $this->load->view("header.php", $datos , TRUE);
		$v_page["banner"] = $this->load->view("banner.html", '' , TRUE);
		$v_page["leftside"] = $this->load->view("leftside", $data , TRUE);

		$mostrarEvento["body"] = $this->load->view("event_view", $datos , TRUE);
		$v_page["centralgrid"] = $this->load->view("centralgrid", $mostrarEvento , TRUE);

		$login["body"] = $this->load->view("login_view", $data, TRUE);
		$login["header"] = "Conectate";
		$v_page["rightside"] = $this->load->view("rightside", $login , TRUE);
		
		$v_page["footer"] = $this->load->view("footer.html", '' , TRUE);
		$this->load->view('index', $v_page);
	}

	public function newUser()
	{
		if (!is_null($this->session->userdata('token')))
		{
			$data['token'] = $this->token();
		} 

		$categorias = $this->Evento_model->getCategorias();
		$tipos = $this->Evento_model->getTipos();

		$selectorCategorias = array();
		while($tablerow = mysql_fetch_array($categorias)) {
 			 $selectorCategorias[$tablerow['id_categoria']] = $tablerow['nombre'];
		}
		$data['categorias'] = $selectorCategorias;

		$selectorTipos = array();
		while($tablerow = mysql_fetch_array($tipos)) {
 			 $selectorTipos[$tablerow['id_tipo']] = $tablerow['nombre'];
		}
		$data['tipos'] = $selectorTipos;

		$datos["inicio"] = '';
		$datos["contact"] = '';
		$datos["unete"] = '';
		$datos["acercaDe"] = '';
		$v_page["header"] = $this->load->view("header.php", $datos , TRUE);
		$v_page["banner"] = $this->load->view("banner.html", '' , TRUE);

		$v_page["leftside"] = $this->load->view("leftside", $data , TRUE);

		$signup["body"] = $this->load->view("signUp_view", $data , TRUE);
		$v_page["centralgrid"] = $this->load->view("centralgrid", $signup , TRUE);

		$login["body"] = $this->load->view("login_view", $data, TRUE);
		$login["header"] = "Conectate";
		$v_page["rightside"] = $this->load->view("rightside", $login , TRUE);
		
		$v_page["footer"] = $this->load->view("footer.html", '' , TRUE);
		$this->load->view('index', $v_page);
	}

	public function checkNewUser()
	{
		$id_usuario = $this->session->userdata('id_usuario');
		if (!is_null($this->session->userdata('token')))
		{
			$data['token'] = $this->token();
		} 

		$this->form_validation->set_rules('nomUsuario', 'nombre de usuario', 'required|trim|min_length[1]|max_length[30]|xss_clean');
        $this->form_validation->set_rules('pass', 'contraseña del usuario', 'required|trim|min_length[1]|max_length[500]|xss_clean');
   		$this->form_validation->set_rules('email', 'email del usuario', 'required|trim|min_length[1]|max_length[30]|xss_clean');
   		$this->form_validation->set_rules('fecha', 'fecha de nacimiento', 'required|trim|min_length[1]|max_length[10]|xss_clean');
   		//$this->form_validation->set_rules('localizacion', 'localizacion', 'required|trim|min_length[1]|max_length[20]|xss_clean');

        //lanzamos mensajes de error si es que los hay
        $this->form_validation->set_message('required', 'El %s es requerido');
        $this->form_validation->set_message('min_length', 'El %s debe tener al menos %s carácteres');
        $this->form_validation->set_message('max_length', 'El %s debe tener al menos %s carácteres');

        if($this->form_validation->run() == FALSE)
        {
        	//$this->index();
        	redirect(base_url()."index.php/welcome/newUser");
        }
        else
        {
        	$nomUsuario = $this->input->post('nomUsuario');
			$pass = sha1($this->input->post('pass'));
			$email = $this->input->post('email');
			$fecha = $this->input->post('fecha');
			$radio = $this->input->post('radio');
			$categorias = $this->Evento_model->getCategorias();
			$selectorEscogidas = array();
			while($tablerow = mysql_fetch_array($categorias)) 
			{
 				 if ($this->input->post($tablerow['nombre']))
 				 {
 				 	$selectorEscogidas[$tablerow['id_categoria']] = $tablerow['id_categoria'];
 				 }
			}

			$usarLocalizacion = $this->input->post('usarLocalizacion');
			$lat = 0;
			$lng = 0;
			
			if ($usarLocalizacion != FALSE)
			{
				$direccion_google = $this->input->post('localizacion');
				$resultado = file_get_contents(sprintf('https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=%s', urlencode($direccion_google)));
				$resultado = json_decode($resultado, TRUE);

				$lat = $resultado['results'][0]['geometry']['location']['lat'];
				$lng = $resultado['results'][0]['geometry']['location']['lng'];
			}

			//$this->Evento_model->saveUser($nomUsuario, $pass, $email, $fecha, $selectorEscogidas, $lat, $lng);
			//$this->sendEmail($email, $nomUsuario, $this->input->post('pass'));
        	if ($id_usuario != null)
        	{
				$userbd = mysql_fetch_assoc($this->Evento_model->getNumUsuarios($id_usuario));
				$this->Evento_model->updateUser($nomUsuario, $pass, $email, $fecha, $selectorEscogidas, $id_usuario, $radio);
        	}
        	else
        	{
        		$textoEmail = 'Le damos la bienvenida a Everent. Estos son sus datos de registro: <br>  <br>
				- Nombre de usuario: '. $nomUsuario .' <br> 
				- Contraseña: '. $this->input->post('pass') .' <br> 
			 Un Saludo. <br> <br>
			 Everent - No te pierdas ningun evento';
			 	$asunto = 'Bienvenido a Everent';

        		$this->Evento_model->saveUser($nomUsuario, $pass, $email, $fecha, $selectorEscogidas, $lat, $lng, $radio);
				$this->sendEmail($email, $textoEmail, $asunto, 'everentcontacto@gmail.com', 'Everent');
        	}
        	$this->index();
        }
	}

	public function unete()
	{
		$id_usuario = $this->session->userdata('id_usuario');
		if (!is_null($this->session->userdata('token')))
		{
			$data['token'] = $this->token();
		} 

		$categorias = $this->Evento_model->getCategorias();
		$tipos = $this->Evento_model->getTipos();

		$selectorCategorias = array();
		while($tablerow = mysql_fetch_array($categorias)) {
 			 $selectorCategorias[$tablerow['id_categoria']] = $tablerow['nombre'];
		}
		$data['categorias'] = $selectorCategorias;

		$selectorTipos = array();
		while($tablerow = mysql_fetch_array($tipos)) {
 			 $selectorTipos[$tablerow['id_tipo']] = $tablerow['nombre'];
		}
		$data['tipos'] = $selectorTipos;
		
		$datos["inicio"] = '';
		$datos["contact"] = '';
		$datos["unete"] = 'class="current_page_item"';
		$datos["acercaDe"] = ''; 
		$v_page["header"] = $this->load->view("header.php", $datos , TRUE);

		$v_page["banner"] = $this->load->view("banner.html", '' , TRUE);

		$v_page["leftside"] = $this->load->view("leftside", $data , TRUE);

		$newEditor["body"] = $this->load->view("unete_view", $data , TRUE);
		$v_page["centralgrid"] = $this->load->view("centralgrid", $newEditor , TRUE);
		
		if ($id_usuario != null)
		{
			$perfil_usuario = mysql_fetch_assoc($this->Evento_model->userProfile($id_usuario));
			if ($perfil_usuario["perfil"] == "suscriptor")
			{
				$data["numRecomendaciones"] = mysql_fetch_assoc($this->Evento_model->getNumRecomendacionesUsuario($this->session->userdata('id_usuario')));
				$suscriptor["body"] = $this->load->view("suscriptor_view", $data, TRUE);
				$suscriptor["header"] = "Bienvenido de Nuevo";
				$v_page["rightside"] = $this->load->view("rightside", $suscriptor , TRUE);	
			}
			else if ($perfil_usuario["perfil"] == "editor")
			{
				$data["eventosPendientes"] = mysql_fetch_assoc($this->Evento_model->getNumEventosPendientesEditor($this->session->userdata('id_usuario')));
				$editor["body"] = $this->load->view("editor_view", $data, TRUE);
				$editor["header"] = "Bienvenido de Nuevo";
				$v_page["rightside"] = $this->load->view("rightside", $editor , TRUE);		
			}
			else if ($perfil_usuario["perfil"] == "administrador")
			{
				$data["eventosPendientes"] = mysql_fetch_assoc($this->Evento_model->getNumEventosPendientesAdmin());
				$data["editoresPendientes"] = mysql_fetch_assoc($this->Evento_model->getNumEditoresPendientesAdmin());
				$admin["body"] = $this->load->view("admin_view", $data, TRUE);
				$admin["header"] = "Bienvenido de Nuevo";
				$v_page["rightside"] = $this->load->view("rightside", $admin , TRUE);	
			}	
		}
		else
		{
			$login["body"] = $this->load->view("login_view", $data, TRUE);
			$login["header"] = "Conectate";
			$v_page["rightside"] = $this->load->view("rightside", $login , TRUE);	
		}
		$v_page["footer"] = $this->load->view("footer.html", '' , TRUE);
		$this->load->view('index', $v_page);
	}

	public function contact()
	{
		$id_usuario = $this->session->userdata('id_usuario');
		if (!is_null($this->session->userdata('token')))
		{
			$data['token'] = $this->token();
		} 

		$categorias = $this->Evento_model->getCategorias();
		$tipos = $this->Evento_model->getTipos();

		$selectorCategorias = array();
		while($tablerow = mysql_fetch_array($categorias)) {
 			 $selectorCategorias[$tablerow['id_categoria']] = $tablerow['nombre'];
		}
		$data['categorias'] = $selectorCategorias;

		$selectorTipos = array();
		while($tablerow = mysql_fetch_array($tipos)) {
 			 $selectorTipos[$tablerow['id_tipo']] = $tablerow['nombre'];
		}
		$data['tipos'] = $selectorTipos;

		$datos["inicio"] = '';
		$datos["contact"] = 'class="current_page_item"';
		$datos["unete"] = '';
		$datos["acercaDe"] = ''; 
		$v_page["header"] = $this->load->view("header.php", $datos , TRUE);
		
		$v_page["banner"] = $this->load->view("banner.html", '' , TRUE);

		$v_page["leftside"] = $this->load->view("leftside", $data , TRUE);

		$newEditor["body"] = $this->load->view("contacto_view", $data , TRUE);
		$v_page["centralgrid"] = $this->load->view("centralgrid", $newEditor , TRUE);

		if ($id_usuario != null)
		{
			$perfil_usuario = mysql_fetch_assoc($this->Evento_model->userProfile($id_usuario));
			if ($perfil_usuario["perfil"] == "suscriptor")
			{
				$data["numRecomendaciones"] = mysql_fetch_assoc($this->Evento_model->getNumRecomendacionesUsuario($this->session->userdata('id_usuario')));
				$suscriptor["body"] = $this->load->view("suscriptor_view", $data, TRUE);
				$suscriptor["header"] = "Bienvenido de Nuevo";
				$v_page["rightside"] = $this->load->view("rightside", $suscriptor , TRUE);	
			}
			else if ($perfil_usuario["perfil"] == "editor")
			{
				$data["eventosPendientes"] = mysql_fetch_assoc($this->Evento_model->getNumEventosPendientesEditor($this->session->userdata('id_usuario')));
				$editor["body"] = $this->load->view("editor_view", $data, TRUE);
				$editor["header"] = "Bienvenido de Nuevo";
				$v_page["rightside"] = $this->load->view("rightside", $editor , TRUE);		
			}
			else if ($perfil_usuario["perfil"] == "administrador")
			{
				$data["eventosPendientes"] = mysql_fetch_assoc($this->Evento_model->getNumEventosPendientesAdmin());
				$data["editoresPendientes"] = mysql_fetch_assoc($this->Evento_model->getNumEditoresPendientesAdmin());
				$admin["body"] = $this->load->view("admin_view", $data, TRUE);
				$admin["header"] = "Bienvenido de Nuevo";
				$v_page["rightside"] = $this->load->view("rightside", $admin , TRUE);	
			}	
		}
		else
		{
			$login["body"] = $this->load->view("login_view", $data, TRUE);
			$login["header"] = "Conectate";
			$v_page["rightside"] = $this->load->view("rightside", $login , TRUE);	
		}
		
		$v_page["footer"] = $this->load->view("footer.html", '' , TRUE);
		$this->load->view('index', $v_page);
	}

	public function newContact()
	{
		if (!is_null($this->session->userdata('token')))
		{
			$data['token'] = $this->token();
		} 

		$this->form_validation->set_rules('nomUsuario', 'nombre de usuario', 'required|trim|min_length[1]|max_length[30]|xss_clean');
   		$this->form_validation->set_rules('email', 'email del usuario', 'required|trim|min_length[1]|max_length[30]|xss_clean');
  
        //lanzamos mensajes de error si es que los hay
        $this->form_validation->set_message('required', 'El %s es requerido');
        $this->form_validation->set_message('min_length', 'El %s debe tener al menos %s carácteres');
        $this->form_validation->set_message('max_length', 'El %s debe tener al menos %s carácteres');

        $nomUsuario = $this->input->post('nomUsuario');
        $asunto = "Contacto del usuario " . $this->input->post('nomUsuario');

		$this->sendEmail('everentcontacto@gmail.com', $this->input->post('descripcion'), $asunto, $this->input->post('email'), $nomUsuario);
        	
        $this->index();
	}

	public function acercaDe()
	{		
		$id_usuario = $this->session->userdata('id_usuario');
		if (!is_null($this->session->userdata('token')))
		{
			$data['token'] = $this->token();
		} 

		$categorias = $this->Evento_model->getCategorias();
		$tipos = $this->Evento_model->getTipos();

		$selectorCategorias = array();
		while($tablerow = mysql_fetch_array($categorias)) 
		{
 			 $selectorCategorias[$tablerow['id_categoria']] = $tablerow['nombre'];
		}
		$data['categorias'] = $selectorCategorias;

		$selectorTipos = array();
		while($tablerow = mysql_fetch_array($tipos)) 
		{
 			 $selectorTipos[$tablerow['id_tipo']] = $tablerow['nombre'];
		}
		$data['tipos'] = $selectorTipos;

		$datos["inicio"] = '';
		$datos["contact"] = '';
		$datos["unete"] = '';
		$datos["acercaDe"] = 'class="current_page_item"';  
		$v_page["header"] = $this->load->view("header.php", $datos , TRUE);
		$v_page["banner"] = $this->load->view("banner.html", '' , TRUE);

		$v_page["leftside"] = $this->load->view("leftside", $data , TRUE);

		$signup["body"] = $this->load->view("acercaDe_view", $data , TRUE);
		$v_page["centralgrid"] = $this->load->view("centralgrid", $signup , TRUE);

		if ($id_usuario != null)
		{
			$perfil_usuario = mysql_fetch_assoc($this->Evento_model->userProfile($id_usuario));
			if ($perfil_usuario["perfil"] == "suscriptor")
			{
				$data["numRecomendaciones"] = mysql_fetch_assoc($this->Evento_model->getNumRecomendacionesUsuario($this->session->userdata('id_usuario')));
				$suscriptor["body"] = $this->load->view("suscriptor_view", $data, TRUE);
				$suscriptor["header"] = "Bienvenido de Nuevo";
				$v_page["rightside"] = $this->load->view("rightside", $suscriptor , TRUE);	
			}
			else if ($perfil_usuario["perfil"] == "editor")
			{
				$data["eventosPendientes"] = mysql_fetch_assoc($this->Evento_model->getNumEventosPendientesEditor($this->session->userdata('id_usuario')));
				$editor["body"] = $this->load->view("editor_view", $data, TRUE);
				$editor["header"] = "Bienvenido de Nuevo";
				$v_page["rightside"] = $this->load->view("rightside", $editor , TRUE);		
			}
			else if ($perfil_usuario["perfil"] == "administrador")
			{
				$data["eventosPendientes"] = mysql_fetch_assoc($this->Evento_model->getNumEventosPendientesAdmin());
				$data["editoresPendientes"] = mysql_fetch_assoc($this->Evento_model->getNumEditoresPendientesAdmin());
				$admin["body"] = $this->load->view("admin_view", $data, TRUE);
				$admin["header"] = "Bienvenido de Nuevo";
				$v_page["rightside"] = $this->load->view("rightside", $admin , TRUE);	
			}	
		}
		else
		{
			$login["body"] = $this->load->view("login_view", $data, TRUE);
			$login["header"] = "Conectate";
			$v_page["rightside"] = $this->load->view("rightside", $login , TRUE);	
		}
		
		$v_page["footer"] = $this->load->view("footer.html", '' , TRUE);
		$this->load->view('index', $v_page);
	}

	public function checkNewEditor()
	{
		if (!is_null($this->session->userdata('token')))
		{
			$data['token'] = $this->token();
		} 

		$this->form_validation->set_rules('nomUsuario', 'nombre de usuario', 'required|trim|min_length[1]|max_length[30]|xss_clean');
        $this->form_validation->set_rules('pass', 'contraseña del usuario', 'required|trim|min_length[1]|max_length[500]|xss_clean');
   		$this->form_validation->set_rules('email', 'email del usuario', 'required|trim|min_length[1]|max_length[30]|xss_clean');
   		$this->form_validation->set_rules('fecha', 'fecha de nacimiento', 'required|trim|min_length[1]|max_length[10]|xss_clean');

        //lanzamos mensajes de error si es que los hay
        $this->form_validation->set_message('required', 'El %s es requerido');
        $this->form_validation->set_message('min_length', 'El %s debe tener al menos %s carácteres');
        $this->form_validation->set_message('max_length', 'El %s debe tener al menos %s carácteres');

        if($this->form_validation->run() == FALSE)
        {
        	//$this->index();
        	redirect(base_url()."index.php/welcome/checkNewEditor");
        }
        else
        {
        	$nomUsuario = $this->input->post('nomUsuario');
			$pass = sha1($this->input->post('pass'));
			$email = $this->input->post('email');
			$fecha = $this->input->post('fecha');
			$descripcion = $this->input->post('descripcion');

			$textoEmail = 'Le damos la bienvenida a Everent. Evaluaremos su candidatura y en caso afirmativo podra 
			empezar a trabajar con nosotros. Estos son sus datos de registro: <br>  <br>
				- Nombre de usuario: '. $nomUsuario .' <br> 
				- Contraseña: '. $this->input->post('pass') .' <br> 
			 Un Saludo. <br> <br>
			 Everent - No te pierdas ningun evento';
			 
			$asunto = 'Bienvenido a Everent';

			$this->sendEmail($email, $textoEmail, $asunto, 'everentcontacto@gmail.com', 'Everent');

			$this->Evento_model->saveEditor($nomUsuario, $pass, $email, $fecha, $descripcion);
        	
        	$this->index();
        }
    }

    public function sendEmail($email, $textoEmail, $asunto, $reply_to, $replyToName)
	{
		$ci = get_instance();
		$ci->load->library('email');
		$config['protocol'] = "smtp";
		$config['smtp_host'] = "ssl://smtp.gmail.com";
		$config['smtp_port'] = "465";
		$config['smtp_user'] = "everentcontacto@gmail.com"; 
		$config['smtp_pass'] = "pfceverent";
		$config['charset'] = "utf-8";
		$config['mailtype'] = "html";
		$config['newline'] = "\r\n";

		$ci->email->initialize($config);

		$ci->email->from('everentcontacto@gmail.com', 'Everent');
		$list = array($email);
		$ci->email->to($list);
		$this->email->reply_to($reply_to, $replyToName);
		$ci->email->subject($asunto);
		$ci->email->message($textoEmail);
		$this->email->attach('images/fotoEmail.jpg');
		$ci->email->send();
	}

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */